<?php
declare (strict_types = 1);

namespace app\controller\backend;

use app\model\Website;
use app\model\WebsiteLang;
use app\model\WebsiteServer;
use app\model\WebsiteSetting;
use app\validate\WebsiteValidate;
use think\facade\Db;
use think\exception\ValidateException;


class WebsiteController extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     */
    public function index(Website $website): \think\response\Json
    {
        $where = [
            'seller_id' => $this->admin['seller_id'],
        ];
        $limit = $this->setLimit();
        $websiteList = $website->getWebsiteList($where,[],$limit);
        return json(pageReturn($websiteList));
    }

    /**
     * 保存新建的资源
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelNotUniqueException
     */
    public function save(Website $website): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            // 数据验证
            try{
                validate(WebsiteValidate::class)->scene('save')->check($param);
            }catch(ValidateException $e){
                return jsonReturn(-1, $e->getError());
            }
            $website->saveUnique(['seller_id'=>$this->admin['seller_id'],'title'=>$param['title']],'网站名称已存在');
            $param['seller_id'] = $this->admin['seller_id'];
            $param['status'] = 1;
            Db::startTrans();
            try{
                // 1. 保存站点到数据库
                $res = $website -> addWebsite($param);
                // 2. 生成一份默认的站点配置，配置的值为空
                $tmpData = [
                    "site_name"=>"",
                    "seo_title"=>"",
                    "seo_keywords"=>"",
                    "seo_description"=>"",
                    "icp"=>"",
                    "gwa"=>"",
                    "admin_email"=>"",
                    "analytics_code"=>"",
                    "author"=>"派流",
                    "icp_link"=>"https://beian.miit.gov.cn/#/Integrated/index",
                    "gwa_link" => "http://www.beian.gov.cn/portal/index.do",
                    "logo"=>"",
                    "customer_code" => "",
                ];
                $sysData = [
                    "setting"=> json_encode($tmpData),
                    "website_id"=>$res['data'],
                    "lang"=>"zh"
                ];
                $siteSetting = new WebsiteSetting();
                $siteSetting -> addWebsiteSetting($sysData);
                // 3. 选择站点语言简体中文，服务器为本地服务器
                $langData[]= [
                    'seller_id' => $this->admin['seller_id'],
                    'website_id'    => $res['data'],
                    'lang_name' => '简体中文',
                    'lang' => 'zh',
                ];
                $WebsiteLang = new WebsiteLang();
                $WebsiteLang->addWebsiteLang($langData);
                $serverData = [
                    'seller_id' => $this->admin['seller_id'],
                    'website_id'    => $res['data'],
                    'type'  => 1,
                ];
                $WebsiteServer = new WebsiteServer();
                $WebsiteServer->addWebsiteServer($serverData);
                Db::commit();
            }catch(\Exception $e){
                Db::rollback();
                return jsonReturn(-5,$e->getMessage());
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 显示指定的资源
     *
     * @return \think\Response
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function read(Website $website): \think\response\Json
    {
        $id = (int)input('id');
        if(!$id){
            return jsonReturn(-1,'网站ID不能为空');
        }
        $where = [
            'id' => $id,
            'seller_id' => $this->admin['seller_id']
        ];
        $res = $website->getWebsite($where);
        return json($res);

    }

    /**
     * 保存更新的资源
     * @return \think\response\Json
     * @throws \app\exception\ModelException
     * @throws \app\exception\ModelEmptyException
     */
    public function update(Website $website): \think\response\Json
    {
        if(request()->isPost()){
            $param = input('post.');
            try {
                validate(WebsiteValidate::class)->scene('update')->check($param);
            } catch (ValidateException $e) {
                return jsonReturn(-1, $e->getError());
            }
            $where = [
                'id' => $param['id'],
                'seller_id' => $this->admin['seller_id'],
            ];
            $site =  $website->getWebsite($where)['data'];
            if($param['domain'] != $site['domain']){
                // 修改路由域名配置
                $routePath = app()->getRootPath() . 'route'. DIRECTORY_SEPARATOR;
                $fileArr = hcScanDir($routePath.'*');
                foreach($fileArr as $val){
                    $siteId = $param['id'];
                    $pattern = '/^'.$siteId.'_/';
                    if(is_file($routePath . $val) && preg_match($pattern,$val)){
                        $conArr =  str_replace($site['domain'],$param['domain'],file_get_contents($routePath.$val));
                        file_put_contents($routePath.$val,$conArr);
                    }
                }
            }
            $res = $website -> updateWebsite($where,$param);
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }

    /**
     * 删除指定资源
     *
     * @throws \app\exception\ModelException
     */
    public function delete(Website $website): \think\response\Json
    {
        if(request()->isPost()){
            $id = (int)input('id');
            if(!$id){
                return jsonReturn(-1,'网站ID不能为空');
            }
            $where = [
                'id' => $id,
                'seller_id' => $this->admin['seller_id']
            ];
            Db::startTrans();
            try {
                // TODO
                // 1、删除站点栏目
                // 2、站点菜单
                // 3、站点主题以及主题下的文件
                // 4、站点主题编辑备份文件
                // 5、站点基本配置
                // 6、站点语言+服务器配置
                // 7、站点路由美化文件
                // 8、删除网站
                $res = $website->delWebsite($where);
                Db::commit();
            }catch (\Exception $e){
                Db::rollback();
               return jsonReturn(-3,$e->getMessage());
            }
            return json($res);
        }
        return jsonReturn(-3,'请求方法错误');
    }
}
